<template>
	<view v-show="isEmpty">
		<LaSwiper :content="goodsData?.goodsImageList" />

		<card :border_bottom="false">
			<!-- <template #coupon>
                <price class="pl-4 py-1" :price="'200元'" :desc="'/台'" />
                <view class="bg-[#fcf0f4] rounded-[14rpx] m-[26rpx] mt-0 p-2">
                    <view class="text-[#DC4C6C] text-xs flex justify-between">
                        <view>无门槛 ￥20 | 满￥50减10</view>
                        <view class="text-right text-[#FEA373]" @click="cheapOpen"
                            >领券 <span class="text-[#DC4C6C]"> ></span></view
                        >
                    </view>
                </view>
            </template> -->
			<view class="goods-price-view">
				<text class="pre-unit">￥</text>
				{{goodsData.price}}
				<text>{{goodsData.unit}}</text>
			</view>
			<view class="goods-title">
				{{goodsData.name}}
			</view>
			<view class="flex justify-between padding">
				<view class="goods-sub-title">
					{{goodsData.remarks}}
				</view>
				<view class="text-xs normal" color="#707070">
					{{ goodsData.orderNum }}人预约过
				</view>
				<!-- <view class="flex" @click="handleCollection(goodsData.collect)">
                    <image
                        class="collection"
                        v-if="!goodsData.collect"
                        src="/static/images/icon_collection.png"
                    >
                    </image>
                    <image
                        class="collection"
                        v-else
                        src="/static/images/icon_collection_s.png"
                    ></image>
                    <text>{{ goodsData.collect ? '取消收藏' : '收藏' }}</text>
                </view> -->
			</view>
			<!-- 规格选择 -->
			<goods-spec ref="goodsSpecRef" :goodsImage="goodsData.goodsImageList" :goodsName="goodsData.name"
				:goodsPrice="goodsData.price" :unitDesc="goodsData.unit" @confirm="handleOrder" />
		</card>

		<!-- 服务师傅 -->
		<!-- <card title="服务师傅">
			<view class="w-full overflow-hidden">
				<scroll-view class="whitespace-nowrap pt-[20rpx] pl-[30rpx]" scroll-x="true">
					<block v-for="item in goodsData.staffList" :key="item.id">
						<view class="w-[100rpx] mr-[54rpx] text-center inline-block" @click="
                                goPage(`/bundle/pages/master_worker_detail/index?id=${item.id}`)
                            ">
							<u-image :src="item?.userVo?.avatar" width="100" height="100" border-radius="50%"></u-image>
							<view class="truncate normal mt-[20rpx] text-base">{{
                                item.name
                            }}</view>
						</view>
					</block>
				</scroll-view>
			</view>
		</card> -->

		<!-- 用户评价 -->
		<card title="用户评价" :url="`/bundle/pages/evaluate_goods/index?id=${goodsId}`">
			<template #header-right>
				<view class="flex text-sm text-muted">
					<text class="mr-[14rpx]">全部评价</text>
					<u-icon name="arrow-right" color="#707070" size="22"></u-icon>
				</view>
			</template>
			<template v-if="goodsData.goods_comment.length">
				<block v-for="commenItem in goodsData.goods_comment" :key="commenItem.id">
					<view class="comment mt-[20rpx]">
						<view class="flex p-[20rpx]">
							<u-image :src="commenItem.avatarUrl" width="80" height="80" border-radius="50%"></u-image>
							<view class="ml-[20rpx]">
								<view class="text-base normal">{{ commenItem.nickname }}</view>
								<view class="text-xs text-muted">{{ commenItem.updateTime }}</view>
							</view>
						</view>
						<view class="text-base normal ml-[20rpx] line-3">{{
                            commenItem.comment
                        }}</view>
					</view>
				</block>
			</template>
			<view class="text-center p-[40rpx] text-muted" v-else> 暂无评价 </view>
		</card>

		<!-- 服务详情 -->
		<view style="padding-bottom: 350rpx">
			<card title="服务详情" :border_bottom="false">
				<view class="p-[24rpx]">
					<mp-html :content="goodsData.content" @imgtap="imgtap" :preview-img="isPreview" />
					<!-- <u-parse :html="goodsData.content" @linkpress="imgtap"></u-parse> -->
				</view>
			</card>
		</view>

		<view class="footer">
			<view>
				<button style="background-color: #3B84D3;"
					class="bg-primary text-lg text-white leading-[80rpx] h-[80rpx]" @click="onAppointment">
					立即预约
				</button>
			</view>
		</view>
	</view>

	<view v-show="!isEmpty" class="empty">
		<u-empty text="抱歉，该服务项目不存在~" :src="'/static/images/empty/collection.png'" :icon-size="300" color="#888888">
			<template #bottom>
				<view class="empty-bottom">
					<button class="bg-primary text-lg text-white leading-[80rpx] h-[80rpx]" @click="goHome">
						去看看其它
					</button>
				</view>
			</template>
		</u-empty>
	</view>

	<cheap-popup ref="cheapRef">
		<template #couponDescOne>
			<view class="text-xs text-[#999]"> 已领取优惠券(共x张) </view>
		</template>
		<template #couponDescTwo>
			<view class="text-xs mt-4 text-[#999]"> 待领取优惠券(共x张) </view>
		</template>
	</cheap-popup>
</template>

<script setup lang="ts">
	import { ref, reactive, shallowRef, unref } from 'vue'
	import { onLoad, onShow, onUnload, onShareAppMessage } from '@dcloudio/uni-app'
	import LaSwiper from '@/components/la-swiper/la-swiper.vue'
	import Card from './components/card.vue'
	import GoodsSpec from './components/goods-spec.vue'
	import Price from '@/components/price/index.vue'
	import { apiGoodsDetail, apiGoodsCollection, apiGoodsCollectionCancel } from '@/api/goods'
	import { apiEvaluateGoodsLists } from '@/api/goods'
	import { removeStorageData } from '@/utils/util'
	import { useUserStore } from '@/stores/user'
	import { useAppStore } from '@/stores/app'
	import { log } from 'console'

	type GOODS = {
		name : string // 服务名称
		remarks : string // 服务简介
		unit : string // 单位描述
		image : string // 主图
		price : string // 价格
		scribingPrice : string // 划线价格
		content : string // 服务详情
		orderNum : string // 预约人数
		collect : string // 是否收藏
		goodsImageList : any // 轮播图
		goods_comment : any // 服务评价
		staffList : any // 服务师傅
		[index : string] : string | number | any
	}

	type TIME = {
		year : string
		date : string
		start_time : string
		end_time : string
	}

	const goodsData = reactive<GOODS>({
		name: '',
		remarks: '',
		unit: '',
		image: '',
		price: '',
		scribingPrice: '',
		content: '',
		orderNum: '',
		collect: '',
		collectId: '',
		goodsImageList: [],
		goods_comment: [],
		staffList: []
	})
	const userStore = useUserStore()
	const isEmpty = ref(true)
	const goodsId = ref<number | string>('')
	const goodsSpecRef = shallowRef<InstanceType<typeof GoodsSpec> | any>()
	const appointTime = ref<TIME>({
		year: '',
		date: '',
		start_time: '',
		end_time: ''
	})
	const isPreview = ref(false)

	// 获取商品详情
	const appStore = useAppStore()
	const initGoodaDetail = async () : Promise<void> => {
		try {
			const res : GOODS = await apiGoodsDetail({
				id: goodsId.value,
				cityId: appStore.cityInfo.city_id
			})
			for (const key in goodsData) {
				if (res[key] != null && res[key] != undefined) {
					goodsData[key] = res[key]
				}
			}
		} catch (error) {
			console.log(error)
			isEmpty.value = false
		}
		getUserEvaluateLists()
	}

	// 获取用户评价
	const getUserEvaluateLists = async () => {
		const { lists } = await apiEvaluateGoodsLists({
			goodsId: +goodsId.value
		})
		goodsData.goods_comment = lists
		console.log('评价：', lists)
	}

	// 收藏操作
	const handleCollection = async (collect : boolean | string | null) : Promise<void> => {
		if (!userStore.isLogin) {
			return uni.$u.toast('请先登录!')
		}
		try {
			collect ? collectionCancel() : collection()
		} catch (error) {
			console.log('收藏请求错误', error)
		}
	}

	// 取消收藏
	const collectionCancel = async () => {
		await apiGoodsCollectionCancel({
			id: unref(goodsData.collectId)
		})
		initGoodaDetail()
	}

	// 收藏
	const collection = async () => {
		await apiGoodsCollection({
			goodsId: unref(goodsId)
		})
		initGoodaDetail()
	}

	// 立即预约
	const onAppointment = () => {
		goodsSpecRef.value.showPop = true
	}

	// 处理预约
	const handleOrder = (goodsNum : number) => {
		try {
			const goods = {
				goods_num: goodsNum,
				id: goodsId.value
			}
			unref(appointTime).date = ''
			if (unref(appointTime).date === '') {
				return goPage(`/bundle/pages/appoint_time/index?params=${JSON.stringify(goods)}`)
			}
			const params = {
				goodsData: goods,
				appointData: unref(appointTime)
			}
			goPage(`/pages/order_buy/index?params=${JSON.stringify(params)}`)
		} catch (error) {
			console.log('处理预约', error)
		}
	}

	const goPage = (url : string) => {
		uni.navigateTo({ url: url })
	}

	const imgtap = (e : Record<string, any>) => {
		if (e['data-href']) {
			// 跳转img中定义的链接
			window.location = e['data-href']
		} else {
			wx.previewImage({
				urls: [e.src] // 仅预览单张图片
			})
		}
	}

	// 返回首页
	const goHome = () => {
		uni.reLaunch({ url: '/pages/index/index' })
	}

	const cheapRef = ref()
	const cheapOpen = () => {
		cheapRef.value.open()
	}

	onShareAppMessage(() => {
		return {
			title: `分享给好友`,
			imageUrl: '123'
		}
	})

	onShow(() => {
		removeStorageData('selectDate')
	})

	onLoad((options) => {
		goodsId.value = options?.id || 0
		initGoodaDetail()

		// 监听上门时间选择
		uni.$on('appointTime', (event : TIME) => {
			appointTime.value = event
		})
	})

	onUnload(() => {
		uni.$off(['appointTime'])
	})
</script>

<style lang="scss">
	.goods-price-view {
		padding: 0 30rpx;
		color: #FF2505;
		font-size: 44rpx;
		font-weight: Bold;
		vertical-align: bottom;

		text {
			font-weight: 400;
			font-size: 22rpx;
		}
		.pre-unit {
			font-size: 24rpx;
		}
	}

	.goods-title {
		padding: 0 30rpx;
		color: #303133;
		font-size: 28rpx;
		line-height: 50rpx;
	}

	.goods-sub-title {
		color: #909399;
		font-size: 22rpx;
		text-align: left;
		line-height: 50rpx;
	}

	// 收藏图标
	.collection {
		width: 44rpx;
		height: 44rpx;
	}

	.padding {
		padding: 0 30rpx;
	}

	.line-3 {
		-webkit-line-clamp: 3;
		overflow: hidden;
		word-break: break-all;
		text-overflow: ellipsis;
		display: -webkit-box; // 弹性伸缩盒
		-webkit-box-orient: vertical; // 设置伸缩盒子元素排列方式
	}

	// 底部按钮
	.footer {
		left: 0;
		bottom: 0;
		width: 100%;
		position: fixed;
		padding: 20rpx 30rpx;
		background-color: #ffffff;
		box-shadow: 2rpx 2rpx 22rpx rgba($color: #000000, $alpha: 0.2);
		padding-bottom: calc(env(safe-area-inset-bottom) + 20rpx);
	}

	// 服务下架或不存在时
	.empty {
		padding-top: 200rpx;

		.empty-bottom {
			width: 90vw;
			margin-top: 130rpx;
		}
	}
</style>